package zz.demo.springCloud.wechat.builder;

import feign.Client;
import feign.Request;
import feign.Retryer;
import feign.auth.BasicAuthRequestInterceptor;
import feign.hystrix.HystrixFeign;
import feign.jackson.JacksonEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zz.demo.springCloud.wechat.entity.ServiceSecurityType;
import zz.demo.springCloud.wechat.entity.WeChatApp;
import zz.demo.springCloud.wechat.feignClient.WeChatFeignClient;


/**
 * Created by zhangzheng on 2017-11-15.
 */
@Component
public class WeChatFeignBuilder {
    private final static String URL_FRONT = "http://";

    @Autowired
    private Client feignClient;

    public WeChatFeignClient securitySelector(WeChatApp weChatApp) {
        if (ServiceSecurityType.BASIC.equals(weChatApp.getSst())) {
            return basicBuilder(weChatApp);
        } else if (ServiceSecurityType.OAUTH2.equals(weChatApp.getSst())) {
            return oauth2Builder(weChatApp);
        }
        return noneBuilder(weChatApp);
    }

    private WeChatFeignClient noneBuilder(WeChatApp weChatApp) {
        return HystrixFeign.builder()
                .client(feignClient)
                .encoder(new JacksonEncoder())
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .target(WeChatFeignClient.class, URL_FRONT + weChatApp.getServiceId());
    }

    private WeChatFeignClient basicBuilder(WeChatApp weChatApp) {
        return HystrixFeign.builder()
                .client(feignClient)
                .encoder(new JacksonEncoder())
//                .decoder(new JacksonDecoder())
                .options(new Request.Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
                .requestInterceptor(new BasicAuthRequestInterceptor(weChatApp.getUsername(), weChatApp.getPassword()))
                .target(WeChatFeignClient.class, URL_FRONT + weChatApp.getServiceId());
    }

    private WeChatFeignClient oauth2Builder(WeChatApp weChatApp) {
        return HystrixFeign.builder()
                .client(feignClient)
//                .requestInterceptor()
                .target(WeChatFeignClient.class, URL_FRONT + weChatApp.getServiceId());
    }

}
